package alex.rsx.http;

import java.io.InputStream;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import alex.rsx.data.RsxBookItem;
import android.os.Bundle;

import com.alex.http.AHandleable;
import com.alex.http.AHandledResult;
import com.alex.http.AHttpRequest;

/**
 * 
 * 排行数据解析
 * 
 * @author Alex.Lu
 *
 */
public class RankHandler implements AHandleable {
	private final String NODE_CODE = "code";
	private final String NODE_REC = "rec";
	private final String NODE_NUM = "num";
	private final String NODE_BOOKID = "bookid";
	private final String NODE_BOOKNAME = "bookname";
	private final String NODE_AUTHOR = "author";
	private final String NODE_WORDCOUNT = "word_count";
	private final String NODE_CLICKCOUNT = "click_count";
	private final String NODE_FAVORITE = "favorite";
	private final String NODE_CREATETIME = "createtime";
	private final String NODE_UPDATETIME = "updatetime";
	
	
	@Override
	public AHandledResult handle(long requestId, String paramString,
			Bundle paramBundle) {
		IndexResponse response = new IndexResponse();
		try {
			JSONObject jsonObject = new JSONObject(paramString);
			response.mCode = jsonObject.getString(NODE_CODE);
			response.mNum = jsonObject.getInt(NODE_NUM);
			JSONArray rec = jsonObject.getJSONArray(NODE_REC);
			for(int i=0;i<response.mNum;i++){
				JSONObject o = rec.getJSONObject(i);
				RsxBookItem item = new RsxBookItem();
				item.mBookId = o.getInt(NODE_BOOKID);
				item.mBookName = o.getString(NODE_BOOKNAME);
				item.mAuthor = o.getString(NODE_AUTHOR);
				item.mWordCount = o.getInt(NODE_WORDCOUNT);
				item.mClickCount = o.getInt(NODE_CLICKCOUNT);
				item.mFavorite = o.getInt(NODE_FAVORITE);
				item.mCreateTime = o.getLong(NODE_CREATETIME);
				item.mUpdateTime = o.getLong(NODE_UPDATETIME);
				response.mBooks.add(item);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new AHandledResult(null,null,response);
	}

	@Override
	public AHandledResult handle(long requestId, InputStream paramInputStream,
			Bundle paramBundle) {
		// TODO Auto-generated method stub
		
		return null;
	}


	@Override
	public int getContentType() {
		// TODO Auto-generated method stub
		return AHttpRequest.TYPE_STRING;
	}

}